package cn.com.huzo.service.tech.impl;

import cn.com.huzo.model.entities.tech.MrpFeedingHeaderEntity;
import cn.com.huzo.repository.purchase.PoNoticeRepository;
import huzofw.model.entities.paginator.Paginator;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.repository.tech.MrpFeedingHeaderRepository;
import cn.com.huzo.repository.tech.MrpFeedingLinesRepository;
import cn.com.huzo.service.tech.MrpFeedingHeaderManager;
import org.apache.commons.collections4.MapUtils;

/**
 * 补料单管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("MrpFeedingHeaderManager")
public class MrpFeedingHeaderManagerImpl extends GenericManagerImpl<MrpFeedingHeaderEntity, Long>
        implements MrpFeedingHeaderManager {

    @Resource(name = "MrpFeedingHeaderRepository")
    private MrpFeedingHeaderRepository _dao;

    @Resource(name = "MrpFeedingLinesRepository")
    private MrpFeedingLinesRepository _dao_lines;

    @Resource(name = "PoNoticeRepository")
    private PoNoticeRepository _dao_po_notice;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public String fetchNewBillNo() throws Exception {
        return _dao.fetchNewBillNo();
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchByHeaderKey(Long headerId, Long currentUserId, Long workFlowId) throws Exception {
        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, currentUserId, workFlowId));
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(headerId));
        // 取得通知的采购担当
        _result.put("PurchasedByNameList", _dao_po_notice.fetchPurchasedByName(headerId, (short)1));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<MrpFeedingHeaderEntity> itemList = _dao.fetchForPage(criterion);
            Paginator<MrpFeedingHeaderEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Long insert(MrpFeedingHeaderEntity instance) throws Exception {
        Long key = _dao.insert(instance);
        // 审计日志
        if (key > 0) {
            writeAuditLog(instance.getUpdatedBy(), "技术管理→补料单", "补料单号：" + instance.getBillNo(), "增加");
        }
        return key;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer update(MrpFeedingHeaderEntity instance) throws Exception {
        Integer rowsAffected = _dao.update(instance);
        // 审计日志
        if (rowsAffected > 0) {
            writeAuditLog(instance.getUpdatedBy(), "技术管理→补料单", "补料单号：" + instance.getBillNo(), "更新");
        }
        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        // 删除
        Integer rowsAffected = _dao.delete(MapUtils.getLong(criterion, "HeaderId"));
        // 审计日志
        if (rowsAffected > 0) {
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "技术管理→补料单", "补料单号：" + MapUtils.getString(criterion, "DeletedBillNo"),
                    "删除");
        }

        return fetchForPage(criterion);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doCheck(Long headerId, Long workFlowId, Short nodeOrder, Long checkedBy, Short isCheckCurrentNode) throws Exception {
        _dao.doCheck(headerId, workFlowId, nodeOrder, checkedBy, isCheckCurrentNode);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, checkedBy, workFlowId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doUnCheck(Long headerId, Long workFlowId, Short nodeOrder, Long checkedBy) throws Exception {
        _dao.doUnCheck(headerId, nodeOrder, checkedBy);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, checkedBy, workFlowId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchPrintPreviewData(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        _result.put("HeaderEntity", _dao.fetchByKey(MapUtils.getLong(criterion, "HeaderKey"),
                MapUtils.getLong(criterion, "CurrentUserId"),
                MapUtils.getLong(criterion, "WorkFlowId")));
        // 取得明细
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(MapUtils.getLong(criterion, "HeaderKey")));

        return _result;
    }
    
    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> setPoOverFlag(Long headerId, Long currentUserId, Long workFlowId, Short poOverFlag) throws Exception {
        Map<String, Object> _result = new HashMap();

        Integer rowsAffected = _dao.setPoOverFlag(headerId, poOverFlag);
        if (rowsAffected > 0) {
            // 如果设置为采购未完成，那么需要返回当前的状态，以利于设置画面元素
            if (poOverFlag == 0) {
                _result.put("HeaderEntity", _dao.fetchByKey(headerId, currentUserId, workFlowId));
            }
        }
        return _result;
    }
}
